<?php
/**
 * 类 PDO 接口 
 *
 * @filesource _pdo.class.php
 * @package peck
 * @subpackage _db
 * @version $id: 0.1, utf8, Mon Jan 11 20:52:01 CST 2010
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2010 MiFunny China Inc.
 * @link http://mifunny.info/
 * @example 
 *   
 */
class _pdo extends PDO{
	/**
	 * @var int $query_count 本次连接所执行的SQL语句数目
	 */
    public $query_count = 0;

    //最后一个sql
    public $last_query;


    public function  __construct(array $policy=null){
        if( empty($policy['dsn']) ){
            throw new LogicException('('.__METHOD__.')'.'Error: database DSN information required!');
        }else{
            //$options = array_merge(array('ATTR_PERSISTENT'=>false,), $policy['driver_options']);
             if( count($policy['options'])>0 ) {
	            foreach($policy['options'] as $k=>$v){
	                $policy['options'][constant('PDO::'.$k)] = $v;
	                unset($policy['options'][$k]);
	            }
             }

            try {
                parent::__construct($policy['dsn'],$policy['username'],$policy['password'],$policy['options']);
                $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); //setFetchMode fetch模式,关联数组
                $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }catch(PDOException $e){
                throw new RuntimeException('('.__METHOD__.')'.'Database Server Connect Error: '.$e->__toString());
            }
        }
    }
    
    public function query($statement){
        ++ $this->query_count;
        $this->last_query = $statement;
        return parent::query($statement);
    }

    public function exec($statement){
        ++ $this->query_count;
        $this->last_query = $statement;
        return parent::exec($statement);
    }


    /**
     * 返回第一行
     * 
     * @param String $statement SQL语句
     * @return array / boolean
     */
    public function getOne($statement){
        $stmt = $this->query($statement);
        if( is_object($stmt) ){
        	return $stmt->fetch();
        }else
        	return false;
    }

    /**
     * 返回全部结果
     * 
     * @param String $statement SQL语句
     * @return array / boolean
     */
    public function getAll($statement){
    	$stmt = $this->query($statement);
        if( is_object($stmt) ){
        	return $stmt->fetchAll();
        }else
        	return false;
    }
    
    /**
     * 检查 链接是否还存在
     * @return boolean
     */
    public function ping(){
        try {
            $this->query('SELECT 1');
            return true;
        } catch (PDOException $e) {
			return false;
        }
    }
    

}//END pdo 

